/**
 * 
 */
package com.a.html5nfc.writer;

import com.a.html5nfc.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Youssef el-Khouri
 * 
 */
public class NFCWriterActivity extends Activity {

    private final static String TAG_WRITER = "NFCWriter";
    String message;
    NfcAdapter mAdapter;
    NFCWriter nfcWriter;
    TextView input;
    boolean writeAndExit = false;
    Button submitButton;
    private IntentFilter[] mWriterFilter;
    private PendingIntent pendingIntent;
    static boolean writeToTag;
    static ProgressDialog dialog;
    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nfcwriter);
        activity = this;
        submitButton = (Button) findViewById(R.id.send_to_nfc);

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        try {
            filter.addDataType("text/plain");
        } catch (MalformedMimeTypeException e) {
            Log.e("TAG", "adding data type to filter generate an error",e);
        }
        mWriterFilter = new IntentFilter[] { filter };
        writeToTag = false;
        nfcWriter = new NFCWriter();
        submitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                    writeToTag = true;
                    message = input.getText().toString();
                    enableTagWriteMode();
                    dialog = ProgressDialog.show(NFCWriterActivity.this, "Write to tag", "Touch the tag to write to it.");
            }
        });
        input = (TextView) findViewById(R.id.inputToWrite);
        Bundle bundle = getIntent().getExtras();
        try {
            message = bundle.getString("input");
        } catch (NullPointerException e) {
            
        }
        if(message != null) {
            input.setText(message);
            writeAndExit = true;
        }        
        dialog = new ProgressDialog(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            message = message.toLowerCase();
            boolean result = nfcWriter.writeToNFCTag(message, tag);
            
            writeToTag = false;
            disableTagWriteMode();
            
            Toast.makeText(this, (result ? "Message sent successfully!" : "Error occurred!"), 3000).show();
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        if(writeAndExit) {
            writeAndExit = false;
            finish();
            activity.finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        super.onResume();
        if(writeAndExit) {
            enableTagWriteMode();
            dialog = ProgressDialog.show(NFCWriterActivity.this, "Write to tag", "Touch the tag to write to it.");
        }
    }
    
    private void enableTagWriteMode() {
        writeToTag = true;
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        mWriterFilter = new IntentFilter[] {
            tagDetected
        };
        mAdapter.enableForegroundDispatch(this, pendingIntent, mWriterFilter, null);
    }
    
    private void disableTagWriteMode() {
        writeToTag = false;
        pendingIntent.cancel(); 
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = null;
        activity = null;
        if(pendingIntent != null && writeToTag) {
            pendingIntent.cancel();
            pendingIntent = null;
        }
    }
}
